package cn.com.zhaoweiping.ie;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Maps;
import java.io.File;
import java.util.Map;
import java.util.Set;

/**
 * <br>
 *
 * @author 冰羽
 * @version 2.2.0
 */
public class ReadContextHolder {

  private static final Map<String, ReadContext> _CONTEXT_ = Maps.newConcurrentMap();

  public static void set(String key, ReadContext val) {
    _CONTEXT_.put(key, val);
    remove();
  }

  public static ReadContext get(String key) {
    return _CONTEXT_.get(key);
  }

  public static void remove(String key) {
    ReadContext readContext = _CONTEXT_.remove(key);
    if (ObjectUtil.isNotEmpty(readContext) && ObjectUtil.isNotEmpty(readContext.getFile())) {
      readContext.getFile().delete();
    }

    remove();
  }

  private static void remove() {
    Set<String> keys = _CONTEXT_.keySet();
    for (String key : keys) {
      ReadContext readContext = get(key);
      if (ObjectUtil.isNotEmpty(readContext) && readContext.removable()) {
        File file = readContext.getFile();
        if (ObjectUtil.isNotEmpty(file)) {
          file.delete();
        }
        _CONTEXT_.remove(key);
      }
    }
  }
}
